package com.sgb.kjwl.view.ui.fragment.home;

import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.BaseHeightViewPagerFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentLeaseMechanicsBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.BannerEntity;
import com.sgb.kjwl.model.entity.BiddingEntity;
import com.sgb.jicai.entity.CentralizedMiningEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.jicai.entity.JiCaiHomeListRequestBean;
import com.sgb.kjwl.model.entity.lease.AskLeaseSheBeiEntity;
import com.sgb.kjwl.model.entity.lease.LeaseListEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.view.event.CategoryEvent2;
import com.swgk.core.event.EventConstant;
import com.sgb.jicai.view.adapter.CentralizedMiningCuttingLineAdapter;
import com.sgb.kjwl.view.ui.adapter.machine.AskLeaseAdapter;
import com.sgb.kjwl.view.ui.adapter.machine.LeaseListAdapter;
import com.sgb.kjwl.view.ui.adapter.pick.PickBidingAdapter;
import com.sgb.kjwl.viewmodel.home.LeasingMachineryModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.decoration.RecyclerViewItemDecoration3;
import com.swgk.core.util.ClickUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;


/**
 * Description:
 * Author cfk
 * Time
 * 租赁市场中的机械fragment
 */
public class LeasingMachineryFragment extends BaseHeightViewPagerFragment {

    @Inject
    LeasingMachineryModel viewModel;
    private FragmentLeaseMechanicsBinding binding;
    List<DictEntity3> dictEntityList;
    private int mItemType;
    private PickSelectEntity entity; //二级类目选中数据
    private DictEntity3 dictEntity3; //租赁大厅-三级类目选中数据
    private PickSelectEntity entity1; //需求大厅-三级类目选中数据
    //机械-适配器
    private LeaseListAdapter leaseListAdapter;
    //需求大厅-求租信息
    private AskLeaseAdapter askLeaseAdapter;
    //竞价租赁
    private PickBidingAdapter pickingAdapter;
    //需求大厅-集采租赁
    private CentralizedMiningCuttingLineAdapter centralizedMiningAdapter;

    public static LeasingMachineryFragment newInstance(int position, BannerEntity bannerEntity, boolean isRefresh) {
        LeasingMachineryFragment fragment = new LeasingMachineryFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM, bannerEntity);
        args.putInt(ARG_PARAM_POS, position);
        args.putBoolean(ARG_isRefresh, isRefresh);
        fragment.setArguments(args);
        return fragment;
    }

    private int getItemType() {
        int mItemType = -1;
        BannerEntity bannerEntity = (BannerEntity) getArguments().getSerializable(ARG_PARAM);
        switch (bannerEntity.getName()) {
            case "租赁大厅":
                mItemType = 0;
                break;
            case "需求大厅":
                mItemType = 1;
                break;
        }
        return mItemType;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_lease_mechanics, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        super.initView();
        if (!EventBus.getDefault().isRegistered(getActivity())) {
            EventBus.getDefault().register(getActivity());
        }
        if (getArguments() == null) {
            return;
        }
        mItemType = getItemType();
        if (mItemType == -1) {
            return;
        }
        if (mItemType == 0) {
            binding.recycler.setLayoutManager(new GridLayoutManager(getContext(), 2));
            binding.recycler.addItemDecoration(new RecyclerViewItemDecoration3(getResources().getDimension(R.dimen.dp10), getResources().getDimension(R.dimen.dp10)));
        } else if (mItemType == 1) {
            binding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));
            binding.recycler.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.bottom = getResources().getDimensionPixelSize(R.dimen.dp1);
                }
            });
        }
        //解决嵌套滑动冲突
        binding.recycler.setNestedScrollingEnabled(false);
        //根据type,请求对应的工程分类
        //出租大厅适配器
        if (leaseListAdapter == null) {
            leaseListAdapter = new LeaseListAdapter(getActivity(), null);
        }
        leaseListAdapter.setOnItemClick(new AdapterOnItemClick<LeaseListEntity>() {
            @Override
            public void onItemClick(LeaseListEntity entity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getH5Url(entity.getType(), entity.getDataId());
                }
            }
        });
        //求租信息
        if (askLeaseAdapter == null) {
            askLeaseAdapter = new AskLeaseAdapter(getActivity(), null);
        }
        askLeaseAdapter.setOnItemClick(new AdapterOnItemClick<AskLeaseSheBeiEntity>() {
            @Override
            public void onItemClick(AskLeaseSheBeiEntity entity, int p) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getH5UrlByAskLease(entity.getType(), entity.getId());
                }
            }
        });
        //竞价租赁
        if (pickingAdapter == null) {
            pickingAdapter = new PickBidingAdapter(getActivity(), null);
        }
        pickingAdapter.setType("");//设置改属性是为了取消多余的标签名称
        pickingAdapter.onIChildClick(new PickBidingAdapter.IChildClick() {
            @Override
            public void onClick(BiddingEntity tenderListEntity) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getUrlSetting(tenderListEntity.getId());
                }
            }
        });
        //集采租赁
        if (centralizedMiningAdapter == null) {
            centralizedMiningAdapter = new CentralizedMiningCuttingLineAdapter(getActivity(), null);
        }
        centralizedMiningAdapter.setOnItemClick(new AdapterOnItemClick<CentralizedMiningEntity>() {
            @Override
            public void onItemClick(CentralizedMiningEntity centralizedMiningEntity, int position) {
                if (!ClickUtils.isDoubleClick()) {
                    viewModel.getH5UrlByJC(centralizedMiningEntity.getNo());
                }
            }
        });
        binding.tvMore.setOnClickListener(v -> loadData(true));
        binding.tvGoModel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 4));
            }
        });
        binding.tvGoModel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 4));
            }
        });
    }

    public void IsRefresh(boolean isRefresh) {
        setIsRefresh(isRefresh);
        loadData(false);
    }

    @Override
    protected void onLazyLoad() {
        viewModel.getSecondType(mItemType);
    }

    @Override
    public void onVisible() {
        super.onVisible();
    }

    private void loadData(boolean isLoadMore) {
        if (viewModel == null) return;
        if (entity == null) return;
        if (mItemType == 0) {
            switch (entity.getNo()) {
                case "0"://租赁大厅全部推荐
                    viewModel.getMachineModel(0, "", isLoadMore);
                    break;
                case "1"://机械推荐
                    viewModel.getMachineModel(1, dictEntity3.getId(), isLoadMore);
                    break;
                case "2"://设备推荐
                    viewModel.getMachineModel(2, dictEntity3.getId(), isLoadMore);
                    break;
                case "3"://车辆推荐
                    viewModel.getAllListByCar(dictEntity3.getId(), isLoadMore);
                    break;
                case "4"://房产推荐
                    viewModel.getAllListByHouse(dictEntity3.getId(), isLoadMore);
                    break;
                case "5"://土地推荐
                    viewModel.getAllListByLand(dictEntity3.getId(), isLoadMore);
                    break;
                case "6"://工厂推荐
                    viewModel.getAllListByFactory(dictEntity3.getId(), isLoadMore);
                    break;
                case "7": //农机推荐
                    viewModel.getAllListByFram(dictEntity3.getId(), isLoadMore);
                    break;
            }
        }
        if (mItemType == 1) {
            switch (entity.getNo()) {
                case "0"://需求大厅-求租信息
                    viewModel.getDataList(entity1.getNo().equals("0") ? "" : String.valueOf(Integer.parseInt(entity1.getNo())), "", isLoadMore);
                    break;
                case "1"://需求大厅-竞价租赁
                    if (entity1.getNo().equals("0")) {//全部
                        viewModel.getBiddingList("", isLoadMore);
                    } else {
                        viewModel.getBiddingList(entity1.getNo(), isLoadMore);
                    }
                    break;
                case "2"://需求大厅-集采租赁
                    JiCaiHomeListRequestBean requestBean = new JiCaiHomeListRequestBean();
                    if (entity1.getNo().equals("0")) {//全部
                        requestBean.setGroupbuyClass("999");//一级类型
                    } else if (entity1.getNo().equals("1")) {//机械
                        requestBean.setGroupbuyClass("2");
                    } else if (entity1.getNo().equals("2")) {//设备
                        requestBean.setGroupbuyClass("3");
                    }
                    requestBean.setTypeNo("");
                    requestBean.setGroupBuyMode("1");//需方发起
                    viewModel.getJiCaiList(requestBean, isLoadMore);
                    break;
            }
        }
    }

    public void showLeaseList(List<LeaseListEntity> list, boolean isLoadMore) {
        if (!isLoadMore)
            binding.recycler.setAdapter(leaseListAdapter);
        updateData(leaseListAdapter, list, isLoadMore, 6);
    }

    public void showAskRentList(List<AskLeaseSheBeiEntity> list, boolean isLoadMore) {
        if (!isLoadMore)
            binding.recycler.setAdapter(askLeaseAdapter);
        updateData(askLeaseAdapter, list, isLoadMore, 3);
    }

    public void showBindingList(List<BiddingEntity> list, boolean isLoadMore) {
        if (!isLoadMore)
            binding.recycler.setAdapter(pickingAdapter);
        updateData(pickingAdapter, list, isLoadMore, 3);
    }

    public void showCentralizedMiningCuttingLineList(List<CentralizedMiningEntity> list, boolean isLoadMore) {
        if (!isLoadMore)
            binding.recycler.setAdapter(centralizedMiningAdapter);
        updateData(centralizedMiningAdapter, list, isLoadMore, 3);
    }

    public <T> void updateData(BaseRecycleAdapter<T> adapter, List<T> list, boolean isLoadMore, int size) {
        //判断是否加载更多
        if (isLoadMore) {
            //判断列表数据是否为空
            if (list != null && list.size() > 0) {
                //适配器设置数据
                adapter.addDatas(list);
                if (list.size() < size) {
                    //当数据少于3个时，隐藏加载更多按钮
                    binding.lineMore.setVisibility(View.VISIBLE);
                    binding.tvMore.setVisibility(View.GONE);
                } else {
                    //当数据数量正常时，默认显示加载更多按钮
                    binding.lineMore.setVisibility(View.VISIBLE);
                }
            } else {
                //当数据返回为空时，隐藏加载更多按钮
                binding.lineMore.setVisibility(View.VISIBLE);
                binding.tvMore.setVisibility(View.GONE);
            }
        } else {
            //判断列表数据是否为空
            if (list != null && list.size() > 0) {
                //当有数据时，显示加载更多按钮，隐藏缺省界面
                binding.lineMore.setVisibility(View.VISIBLE);
                if (list.size() < size) {
                    //当数据少于3个时，隐藏加载更多按钮
                    binding.tvMore.setVisibility(View.GONE);
                } else {
                    binding.tvMore.setVisibility(View.VISIBLE);
                }
                binding.emptyView.setVisibility(View.GONE);
            } else {
                //当有数据时，隐藏加载更多按钮，显示缺省界面
                binding.lineMore.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
            //适配器设置数据
            adapter.setDatas(list);
        }
    }

    //从适配器中获取前三个数据的缓存
    public <T> void loadCacheData(BaseRecycleAdapter<T> adapter) {
        List<T> data = adapter.getDatas();
        if (data != null && data.size() > viewModel.pageNum) {
            List<T> tempList = new ArrayList<>();
            tempList.add(data.get(0));
            tempList.add(data.get(1));
            tempList.add(data.get(2));
            adapter.setDatas(tempList);
        }
    }

    public void showType(List<DictEntity3> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        dictEntityList = data;
        for (int i = 0; i < data.size(); i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(data.get(i).getName()));
        }
    }

    /*
     * 租赁二级类目数据
     * */
    public void showLeaseTypeView(List<PickSelectEntity> data) {
        binding.tabLayout.clearOnTabSelectedListeners();
        binding.tabLayout.removeAllTabs();
        for (int i = 0; i < data.size(); i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(data.get(i).getProjectscale()));
        }
        binding.tabLayout.scrollTo(0, 0);
        entity = data.get(0);
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                entity = data.get(tab.getPosition());
                if (tab.getPosition() == 0) {
                    binding.tabLayoutType.setVisibility(View.GONE);
                    loadData(false);
                    return;
                }
                viewModel.getThreeTypeModel(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        loadData(false);
    }

    /*
     * 租赁三级类目数据
     * */
    public void showLeaseThreeTypeView(List<DictEntity3> data) {
        binding.tabLayoutType.setVisibility(View.VISIBLE);
        binding.tabLayoutType.clearOnTabSelectedListeners();
        binding.tabLayoutType.removeAllTabs();
        for (int i = 0; i < data.size(); i++) {
            binding.tabLayoutType.addTab(binding.tabLayoutType.newTab().setText(data.get(i).getName()));
        }
        binding.tabLayoutType.scrollTo(0, 0);
        dictEntity3 = data.get(0);
        binding.tabLayoutType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                dictEntity3 = data.get(tab.getPosition());
                loadData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        loadData(false);
    }

    /*
     * 需求大厅二级类目数据
     * */
    public void showLeaseNeedView(List<PickSelectEntity> data) {
        binding.tabLayout.clearOnTabSelectedListeners();
        binding.tabLayout.removeAllTabs();
        for (int i = 0; i < data.size(); i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(data.get(i).getProjectscale()));
        }
        binding.tabLayout.scrollTo(0, 0);
        entity = data.get(0);
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                entity = data.get(tab.getPosition());
                viewModel.getThreeTypeNeedModel(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        viewModel.getThreeTypeNeedModel(0);
    }

    /*
     * 需求大厅三级类目数据
     * */
    public void showThreeLeaseNeedView(List<PickSelectEntity> data) {
        binding.tabLayoutType.setVisibility(View.VISIBLE);
        binding.tabLayoutType.clearOnTabSelectedListeners();
        binding.tabLayoutType.removeAllTabs();
        for (int i = 0; i < data.size(); i++) {
            binding.tabLayoutType.addTab(binding.tabLayoutType.newTab().setText(data.get(i).getProjectscale()));
        }
        binding.tabLayoutType.scrollTo(0, 0);
        entity1 = data.get(0);
        binding.tabLayoutType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                entity1 = data.get(tab.getPosition());
                loadData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        loadData(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
